package com.example.photo.controller;

import com.example.photo.common.AuthCheck;
import com.example.photo.common.BaseResponse;
import com.example.photo.common.ErrorCode;
import com.example.photo.common.TokenRefresh;
import com.example.photo.exception.BusinessException;
import com.example.photo.model.VO.UserVO;
import com.example.photo.model.domain.User;
import com.example.photo.model.request.CommonRegisterRequest;
import com.example.photo.model.request.LoginRequest;
import com.example.photo.model.request.update.UpdateUserRequest;
import com.example.photo.service.UserService;
import com.example.photo.utils.JwtTokenUtils;
import com.example.photo.utils.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author Lwh
 * @time 2023/03/26 13:40
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 普通用户注册
     */
    @PostMapping("/register/common")
    public BaseResponse<Integer> commonRegister(@RequestBody CommonRegisterRequest registerRequest,
                                                HttpServletResponse response) {
        if (registerRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        String username = registerRequest.getUsername();
        String password = registerRequest.getPassword();
        String checkPassword = registerRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(username, password, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        UserVO userVO = userService.commonUserRegister(username, password, checkPassword, response);
        if (userVO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "普通用户注册失败");
        }
        return ResultUtils.success(userVO.getUserId());
    }

    /**
     * 发送验证码
     *
     * @param email 邮箱
     */
    @PostMapping("/send")
    public BaseResponse<Boolean> sendCode(@RequestParam String email,
                                          HttpServletRequest request) {
        if (StringUtils.isBlank(email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        userService.sendCode(email, request);
        return ResultUtils.success(true);
    }

    /**
     * 检查 验证码
     *
     * @param email 邮箱
     * @param code  验证码
     */
    @PostMapping("/verify")
    public BaseResponse<Boolean> verifyCode(@RequestParam String email,
                                            @RequestParam String code,
                                            HttpServletRequest request) {
        if (StringUtils.isAnyBlank(email, code)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.verifyCode(email, code, request);

        return ResultUtils.success(b);
    }

    /**
     * 普通用户、管理员使用账号密码登录
     * TODO “记住我”功能
     */
    @PostMapping("/login/common")
    public BaseResponse<UserVO> loginByCommon(@RequestBody LoginRequest loginRequest,
                                              HttpServletResponse response) {
        if (loginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        if (StringUtils.isAnyBlank(username, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        UserVO userVO = userService.commonUserLogin(username, password, response);
        if (userVO == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户登录失败");
        }
        return ResultUtils.success(userVO);
    }

    /**
     * 通过用户中心登录
     * 第一次 708ms
     * 第二次 50ms
     */
    @PostMapping("/login/tju")
    public BaseResponse<UserVO> loginByUsercenter(@RequestBody LoginRequest loginRequest,
                                                  HttpServletResponse response) {
        if (loginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        if (StringUtils.isAnyBlank(username, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        UserVO userVO = userService.tjuUserLogin(username, password, response);
        if (userVO == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户登录失败");
        }
        return ResultUtils.success(userVO);
    }

    /**
     * 用户修改个人信息
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @PostMapping("/update")
    public BaseResponse<UserVO> updateUserInfo(@RequestBody UpdateUserRequest updateUserRequest,
                                               HttpServletRequest request) {
        if (updateUserRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //判断修改的是否是当前登录用户的信息
        Integer currentUserId = Integer.valueOf(request.getHeader(JwtTokenUtils.USERID_HEADER));
        Integer userId = updateUserRequest.getUserId();
        if (!Objects.equals(userId, currentUserId)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权修改其他用户的信息");
        }
        //不允许修改头像
        updateUserRequest.setAvatar(null);
        //修改用户信息
        boolean update = userService.updateById(new User(updateUserRequest));
        if (!update) {
            throw new BusinessException(ErrorCode.SERVER_ERROR, "修改用户信息失败");
        }
        //重新查询当前用户信息并返回
        return ResultUtils.success(new UserVO(userService.getById(currentUserId)));
    }

    /**
     * 用户修改密码
     *
     * @param email       邮箱
     * @param code        邮箱验证码
     * @param newPassword 新密码
     */
    @PostMapping("/reset")
    public BaseResponse<Boolean> resetPassword(@RequestParam String email,
                                               @RequestParam String code,
                                               @RequestParam String newPassword,
                                               HttpServletRequest request) {
        if (StringUtils.isAnyBlank(email, code, newPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        userService.verifyCode(email, code, request);
        userService.resetPassword(email, newPassword);

        return ResultUtils.success(true);
    }

    /**
     * 根据用户id获取昵称和头像
     */
    @GetMapping("/info")
    public BaseResponse<UserVO> getInfoById(@RequestParam Integer userId) {
        if (userId < 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "该用户不存在");
        }
        return ResultUtils.success(new UserVO(user));
    }


    /**
     * 功能测试接口
     */
    @AuthCheck
    @TokenRefresh
    @GetMapping("/get")
    public BaseResponse<Integer> get(HttpServletRequest request) {
        String header = request.getHeader(JwtTokenUtils.ROLE_HEADER);
        System.out.println(header);
        return ResultUtils.success(1);
    }

}
